package com.cloudpivot.receivales.crm.controller;

import com.cloudpivot.receivales.crm.entity.weekly.WeeklyCount;
import com.cloudpivot.receivales.crm.service.WeeklyCountServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 周报 报表接口
 */
@Controller
@Slf4j
@RequestMapping("/weekly")
public class WeeklyCountController {

    @Autowired
    private WeeklyCountServiceImpl weeklyCountService;

    @GetMapping(value = "getWeeklyReport")
    public List<WeeklyCount> getWeeklyCounts(@RequestParam(value = "unitid") String unitid, @RequestParam(value = "starttime") String starttime, @RequestParam(value = "endtime") String endtime) {
        if (StringUtils.isBlank(unitid)) {
            return null;
        }
        if (StringUtils.isBlank(starttime) || StringUtils.isBlank(endtime)) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String date_now = formatter.format(new Date());
            starttime = getStartForEmpty(date_now);
            endtime = getEndForEmpty(date_now);
        }
        //校验starttime 和 endtime 如果为空取当前月
        List<WeeklyCount> lists = weeklyCountService.getList(unitid, starttime, endtime);
        return lists;
    }

    /**
     * 获取月初
     * @return
     */
    private String getStartForEmpty(String date_str) {
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            Calendar cale = Calendar.getInstance();
            cale.setTime(formatter.parse(date_str));
            cale.add(Calendar.MONTH, 0);
            cale.set(Calendar.DAY_OF_MONTH, 1);
            String s = formatter.format(cale.getTime()) + " 00:00:00";
            return s;
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取月末
     * @return
     */
    private String getEndForEmpty(String date_str) {
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            Calendar cale = Calendar.getInstance();
            cale.setTime(formatter.parse(date_str));
            cale.add(Calendar.MONTH, 1);
            cale.set(Calendar.DAY_OF_MONTH, 0);
            String s=formatter.format(cale.getTime()) + " 23:59:59";
            return s;
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }
}
